package cn.aws360.boot.extend.sms.sdk;

import cn.aws360.boot.base.api.constant.BaseConstant;
import cn.aws360.boot.base.api.exception.ServiceException;
import cn.aws360.boot.extend.sms.api.SmsSenderApi;
import cn.aws360.boot.extend.sms.api.exception.SmsExceptionEnum;
import cn.aws360.boot.extend.sms.api.pojo.properties.TencentSmsProperties;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;

/**
 * @author junnan
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = BaseConstant.APP + ".extend.sms.tencent.enable", havingValue = "true")
public class TencentSmsServiceSdk implements SmsSenderApi {

    private final static String PREFIX = "+86";
    private final static String REGION = "ap-guangzhou";
    private final TencentSmsProperties smsProperties;

    @Override
    public Boolean sendSms(String sign, String tplId, String mobile, Map<String, Object> paramMap) {
        Credential credential = new Credential(smsProperties.getSecretId(), smsProperties.getSecretKey());
        SmsClient smsClient = new SmsClient(credential, REGION);

        SendSmsRequest request = new SendSmsRequest();
        request.setSmsSdkAppid(smsProperties.getSdkAppId());
        request.setSign(sign);
        request.setTemplateID(tplId);
        request.setPhoneNumberSet(new String[]{PREFIX + mobile});

        String[] paramArr = paramMap.values().stream().map(Object::toString).toArray(String[]::new);
        request.setTemplateParamSet(paramArr);

        try {
            SendSmsResponse response = smsClient.SendSms(request);
            log.info("【短信发送结果-腾讯】response: {}", SendSmsResponse.toJsonString(response));
            long okCount = Arrays.stream(response.getSendStatusSet()).filter(s -> "ok".equalsIgnoreCase(s.getCode())).count();
            return okCount == response.getSendStatusSet().length;
        } catch (Exception e) {
            throw new ServiceException(SmsExceptionEnum.SMS_SEND_ERROR_FOR_TENCENT);
        }
    }

}
